package es.ikex.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.RequestContext;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;

import es.ikex.dao.SliderDao;


public class NuevaFotoSlider extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		Iterator<FileItem> iterator = null;
		try {
			iterator = upload.parseRequest((RequestContext)request).iterator();
		} catch (FileUploadException e1) {
			e1.printStackTrace();
		}
		File uploadedFile;
		//String dirPath = "C:\\eclipse-jee-muebles\\WorkSpace\\Muebles\\WebContent\\img\\slider\\fotos";
		//String dirPath = "C:\\Tomcat7\\webapps\\Muebles\\img\\slider\\fotos";
		String dirPath = "/usr/local/tomcat/webapps/Muebles/img/slider/fotos";
		//String dirPath = "/img/muebles/slider/fotos";
		
		String nombre = "";
		String id = "";
		String foto = "";
		String efecto = "";
		while (iterator.hasNext()) {
			FileItem item = iterator.next();
			if (!item.isFormField()) {
				foto = nombre + item.getName().substring(item.getName().lastIndexOf('.'), item.getName().length());
				
				String fileNameWithExt = foto;

				File filePath = new File(dirPath);
				
				if (!filePath.exists()) {
					filePath.mkdirs();
				}
				uploadedFile = new File(dirPath + "/" + fileNameWithExt);
				try {
					item.write(uploadedFile);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				if(item.getFieldName().equals("id")){
					id = item.getString();
				}else if(item.getFieldName().equals("nombre")){
					nombre = item.getString();
					nombre.replace(" ", "");
				}else if(item.getFieldName().equals("efecto")){
					efecto = item.getString();
				}
			}
		}
		
		SliderDao sl = new SliderDao();
		sl.modificarSlider(Integer.parseInt(id), foto, nombre, efecto);
		request.getRequestDispatcher("/Admin/slider.jsp").forward(request, response);
	}
	
}
